<template>
  <div class="main-container">
    <el-container>
      <el-aside width="220px" class="sidebar">
        <div class="logo">
          <span class="logo-icon">AI</span>
          <span class="logo-text">AI知识库问答</span>
        </div>
        <el-menu
          router
          :default-active="activeMenu"
          class="el-menu-vertical"
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
        >
          <el-menu-item index="/main/chat" class="menu-item">
            <el-icon><ChatDotRound /></el-icon>
            <span>智能问答</span>
          </el-menu-item>
          <el-menu-item index="/main/knowledge" class="menu-item">
            <el-icon><Collection /></el-icon>
            <span>知识库</span>
          </el-menu-item>
          <el-menu-item index="/main/upload" class="menu-item">
            <el-icon><Upload /></el-icon>
            <span>文件上传</span>
          </el-menu-item>
        </el-menu>
        <div class="sidebar-footer">
          <span>© 2025 MyAI</span>
        </div>
      </el-aside>
      <el-container class="main-content">
        <el-header class="header">
          <div class="header-left">
            <h2 class="page-title">{{ getPageTitle }}</h2>
          </div>
          <div class="header-right">
            <div class="time-display">{{ currentTime }}</div>
            <el-dropdown trigger="click">
              <span class="user-info">
                <el-avatar size="small" class="user-avatar" :icon="UserFilled" />
                <span>{{ displayUsername }}</span>
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleLogout">
                    <el-icon><SwitchButton /></el-icon>
                    <span>退出登录</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <el-main class="main-area">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { UserFilled, ChatDotRound, Collection, Upload, SwitchButton, ArrowDown } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { userApi } from '@/api'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const currentTime = ref(formatTime(new Date()))
let timer = null

// 格式化时间为 HH:MM:SS
function formatTime(date) {
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${hours}:${minutes}:${seconds}`
}

// 更新当前时间
function updateTime() {
  currentTime.value = formatTime(new Date())
}

// 获取当前页面标题
const getPageTitle = computed(() => {
  const path = route.path
  if (path.includes('/chat')) return '智能问答'
  if (path.includes('/knowledge')) return '知识库'
  if (path.includes('/upload')) return '文件上传'
  return 'MyAI 智能助手'
})

const activeMenu = computed(() => {
  return route.path
})

/**
 * 获取用户显示名称
 * 优先显示用户名，如果没有则显示默认值
 * @returns {string} - 用户显示名称
 */
const displayUsername = computed(() => {
  return authStore.userInfo?.username || '用户'
})

/**
 * 获取用户信息
 * 如果当前没有用户信息或用户信息不完整，则调用API获取
 */
const fetchUserInfo = async () => {
  try {
    if (authStore.isAuthenticated) {
      // 如果没有用户信息或用户信息不完整，则获取
      if (!authStore.userInfo || !authStore.userInfo.username) {
        console.log('正在获取用户信息...')
        const response = await userApi.getUserInfo()
        if (response && response.data) {
          authStore.setUserInfo({
            id: response.data.id,
            username: response.data.username
          })
          console.log('用户信息获取成功:', response.data)
        }
      } else {
        console.log('用户信息已存在:', authStore.userInfo)
      }
    } else {
      console.log('用户未认证，跳过获取用户信息')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 如果获取失败，不影响页面正常显示
  }
}

/**
 * 处理退出登录
 * 使用认证store统一处理退出登录逻辑
 */
const handleLogout = () => {
  ElMessageBox.confirm('确认退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 使用认证store的退出登录方法
      await authStore.logout()
      
      // 跳转到登录页
      router.push('/login')
    } catch (error) {
      console.error('退出登录失败:', error)
      // 即使出错也跳转到登录页
      router.push('/login')
    }
  }).catch(() => {})
}

// 组件挂载时启动定时器并获取用户信息
onMounted(() => {
  updateTime()
  timer = setInterval(updateTime, 1000)
  fetchUserInfo()
})

// 组件卸载前清除定时器
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.main-container {
  height: 100vh;
  overflow: hidden;
}

.sidebar {
  background-color: #304156;
  color: #fff;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  position: relative;
  z-index: 10;
  height: 100vh;
}

.logo {
  height: 60px;
  padding: 0 16px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.logo-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #42b983, #33a06f);
  border-radius: 8px;
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
  box-shadow: 0 2px 6px rgba(66, 185, 131, 0.4);
}

.logo-text {
  font-size: 18px;
  font-weight: bold;
  background: linear-gradient(to right, #ffffff, #bfcbd9);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

.el-menu-vertical {
  border-right: none;
  flex: 1;
}

.menu-item {
  margin: 4px 0;
  border-radius: 4px;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

.sidebar-footer {
  padding: 16px;
  font-size: 12px;
  color: #8a9ab1;
  text-align: center;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.main-content {
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.header {
  background-color: #fff;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 5;
}

.header-left {
  display: flex;
  align-items: center;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  position: relative;
}

.page-title::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 0;
  width: 30px;
  height: 3px;
  background: linear-gradient(to right, #42b983, #33a06f);
  border-radius: 3px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.time-display {
  font-size: 14px;
  color: #606266;
  background-color: #f5f7fa;
  padding: 4px 12px;
  border-radius: 16px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 6px 10px;
  border-radius: 20px;
  transition: all 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.user-avatar {
  background: linear-gradient(135deg, #42b983, #33a06f);
  margin-right: 8px;
}

.user-info span {
  margin: 0 8px;
}

.main-area {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

/* 页面过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>